import React from 'react';
import { Button, DatePicker, Input, message, Select } from 'antd';
import styles from './styles/index.less';
import { SelectValue } from 'antd/es/select';
import { Moment } from 'moment';
import { RangePickerValue } from 'antd/es/date-picker/interface';
import { getAreaList, getTypeList, getCreateUser } from '@/pages/routes/table/service';

const { RangePicker } = DatePicker;
const { Option, OptGroup } = Select;

export interface QueryObject {
  name: string;
  type: number;
  area: number;
  createUser: number;
  /**
   * 本点号
   */
  bdh: string;
  updateDate: [string, string];
  startDate: [string, string];
  endDate: [string, string];
}

interface QueryFormProps {
  onQuery: (options: QueryObject) => void;
}

export interface EnumObject {
  title: string;
  value: number;
}

type TimeRange = [Moment | undefined, Moment | undefined];

interface QueryFormState {
  name: string;
  type: number;
  area: number;
  createUser: number;
  /**
   * 本点号
   */
  bdh: string;
  updateDate: TimeRange;
  startDate: TimeRange;
  endDate: TimeRange;
  typeList: EnumObject[];
  areaList: EnumObject[];
  createUserList: EnumObject[];
}

class QueryForm extends React.Component<QueryFormProps, QueryFormState> {
  public state: QueryFormState = {
    name: '',
    type: -1,
    area: -1,
    createUser: -1,
    bdh: '',
    updateDate: [undefined, undefined],
    startDate: [undefined, undefined],
    endDate: [undefined, undefined],
    typeList: [],
    areaList: [],
    createUserList: [],
  };

  componentDidMount() {
    this.loadAreaList();
    this.loadTypeList();
    this.loadCreateList();
  }

  public async loadAreaList() {
    try {
      const { code, data } = await getAreaList();
      if (code === 0) {
        this.setState({ areaList: [{ title: '全部', value: -1 }].concat(data) });
        return;
      }
      message.error('获取区域列表失败了');
    } catch (e) {
      console.error(e);
      message.error('获取区域列表失败了');
    }
  }

  public async loadTypeList() {
    try {
      const { code, data } = await getTypeList();
      if (code === 0) {
        this.setState({ typeList: [{ title: '全部', value: -1 }].concat(data) });
        return;
      }
      message.error('获取方案类型列表失败了');
    } catch (e) {
      console.error(e);
      message.error('获取方案类型列表失败了');
    }
  }

  public async loadCreateList() {
    try {
      const { code, data } = await getCreateUser();
      if (code === 0) {
        this.setState({ createUserList: [{ title: '全部', value: -1 }].concat(data) });
        return;
      }
      message.error('获取编制人列表失败了');
    } catch (e) {
      console.error(e);
      message.error('获取编制人列表失败了');
    }
  }

  public handleChange = (value: SelectValue) => {
    this.setState({ type: value as number });
  };
  public handleAreaChange = (value: SelectValue) => {
    this.setState({ area: value as number });
  };
  public handleCreateUserChange = (value: SelectValue) => {
    this.setState({ createUser: value as number });
  };
  public onChange = (value: RangePickerValue, key: 'updateDate' | 'startDate' | 'endDate') => {
    this.setState({ [key]: value as [Moment, Moment] } as any);
  };

  render() {
    const { typeList, areaList, type, createUser, area, bdh, name, updateDate, startDate, endDate, createUserList } =
      this.state;
    return (
      <div>
        <div className={styles.queryform}>
          <div>
            <label className={styles.formLabel}>方案名称：</label>
            <div className={styles.formInput} style={{ width: 150 }}>
              <Input
                value={name}
                placeholder={'请输入'}
                onChange={({ target: { value } }) => this.setState({ name: value })}
              />
            </div>
          </div>
          <div>
            <label className={styles.formLabel}>方案类型：</label>
            <div className={styles.formInput} style={{ width: 150 }}>
              <Select value={type} style={{ width: 150 }} onChange={this.handleChange}>
                {typeList.map(({ title, value }) => (
                  <Option key={value} value={value}>
                    {title}
                  </Option>
                ))}
              </Select>
            </div>
          </div>
          <div>
            <label className={styles.formLabel}>所属区域：</label>
            <div className={styles.formInput} style={{ width: 150 }}>
              <Select value={area} style={{ width: 150 }} onChange={this.handleAreaChange}>
                {areaList.map(({ title, value }) => (
                  <Option key={value} value={value}>
                    {title}
                  </Option>
                ))}
              </Select>
            </div>
          </div>
          <div>
            <label className={styles.formLabel}>编制人：</label>
            <div className={styles.formInput} style={{ width: 150 }}>
              <Select value={createUser} onChange={this.handleCreateUserChange}>
                {createUserList.map(({ title, value }) => (
                  <Option key={value} value={value}>
                    {title}
                  </Option>
                ))}
              </Select>
            </div>
          </div>
          <div>
            <label className={styles.formLabel}>本点号：</label>
            <div className={styles.formInput}>
              <Input
                value={bdh}
                placeholder={'请输入'}
                onChange={({ target: { value } }) => this.setState({ bdh: value })}
              />
            </div>
          </div>
        </div>

        <br />
        <label className={styles.formLabel}>更新时间：</label>
        <div className={styles.formInput} style={{ width: 150 }}>
          <RangePicker
            value={updateDate as [Moment, Moment]}
            onChange={(value) => this.onChange(value, 'updateDate')}
          />
        </div>
        <label className={styles.formLabel}>开始时间：</label>
        <div className={styles.formInput} style={{ width: 250 }}>
          <RangePicker value={startDate as [Moment, Moment]} onChange={(value) => this.onChange(value, 'startDate')} />
        </div>
        <label className={styles.formLabel}>结束时间：</label>
        <div className={styles.formInput} style={{ width: 233 }}>
          <RangePicker value={endDate as [Moment, Moment]} onChange={(value) => this.onChange(value, 'endDate')} />
        </div>
        <br />
        <div className={styles.mainBtn}>
          <Button type={'primary'} onClick={this.handleQueryClick}>
            查询
          </Button>
          <Button style={{ marginLeft: 10 }} onClick={this.handleResetClick}>
            重置
          </Button>
        </div>
      </div>
    );
  }

  private query = () => {
    const { name, type, area, createUser, bdh, updateDate, startDate, endDate } = this.state;
    const { onQuery } = this.props;
    if (startDate[0] && endDate[1]) {
      if (startDate[0]!.isAfter(endDate[1])) {
        message.info('结束时间的终止值必须大于开始时间的起始值');
        return;
      }
    }
    const formatStr = 'YYYY-MM-DD 00:00:00';
    const fn = ([t1, t2]: TimeRange) =>
      [t1 ? t1.format(formatStr) : '', t2 ? t2.format(formatStr) : ''] as [string, string];
    onQuery?.({
      name: name.trim(),
      type,
      area,
      createUser,
      bdh,
      updateDate: fn(updateDate),
      startDate: fn(startDate),
      endDate: fn(endDate),
    });
    // 验证参数
  };

  private handleQueryClick = () => {
    this.query();
  };
  private handleResetClick = () => {
    //
    // 还原到默认值
    this.setState(
      {
        name: '',
        type: -1,
        area: -1,
        createUser: -1,
        bdh: '',
        updateDate: [undefined, undefined],
        startDate: [undefined, undefined],
        endDate: [undefined, undefined],
        typeList: [],
        areaList: [],
      },
      this.query
    );
  };
}

export default QueryForm;
